<?php
class WDealAdminExport extends UWidgetWorklet
{	
	public function accessRules()
	{
		return array(
			array('allow', 'roles' => array('company')),
			array('deny', 'users'=>array('*'))
		);
	}
	
	public function taskConfig()
	{
		$list = wm()->get('deal.admin.coupon');
		$_GET[$list->modelClassName] = $_POST[$list->modelClassName];
		$list->init();
		$dataProvider = $list->dataProvider();
		$dataProvider->pagination = false;
		
		$csv = array(
			array(
				$this->t('ID'),
				$this->t('Order ID'),
				$this->t('Deal ID'),
				$this->t('User'),
				$this->t('Status'),
			)
		);
		
		foreach($dataProvider->data as $data)
		{
			$row = array(
				"#".$data->couponId(),
				$data->orderId,
				$data->dealId,
				$data->user->email." [".$data->user->getName(true)."]",
				$data->status==1
					? ($data->deal->isExpired() ? $this->t('Expired') : $this->t('Available'))
					: $this->t('Used')
			);
			
			if($_POST['charset'] != 'utf-8')
			{
				$row[3] = iconv('utf-8', $_POST['charset'], $row[3]);
				$row[4] = iconv('utf-8', $_POST['charset'], $row[4]);
			}
			
			$csv[] = $row;
		}
		
		$contents = $this->generateCSV($csv);
		$this->send($contents);
	}
	
	public function taskGenerateCSV($src)
	{
		$csv = '';
		foreach($src as $row)
		{
			foreach($row as $item)
				$csv.= $this->escape($item).$this->param('delimiter');
			$csv = rtrim($csv,$this->param('delimiter'))."\r\n";
		}
		return $csv;
	}
	
	public function taskEscape($value)
	{
		return '"'.str_replace('"','""',$value).'"';
	}
	
	public function taskSend($contents)
	{
		$content_type = "application/octet-stream";
		$filename = 'export.csv';
		
		// disable browser caching
		header('Cache-control: private');
		header('Pragma: private');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		
		header('Content-Type: '.$content_type);
		header('Content-Transfer-Encoding: binary');
		header('Content-Length: '.strlen($contents));
		header('Content-Disposition: attachment;filename="'.$filename.'"');
		
		echo $contents;
		app()->end();
	}
}